package com.shop.service.impl;

import com.shop.entity.SysUser;
import com.shop.entity.SysUserRole;
import com.shop.entity.dto.RolePerssionDTO;
import com.shop.mapper.SysUserMapper;
import com.shop.mapper.SysUserRoleMapper;
import com.shop.service.SysUserService;
import com.shop.utils.PageUtils;
import com.shop.utils.ResultUtils;
import com.shop.utils.ShiroPasswordUtils;
import com.shop.utils.StringEmptyUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author  huangfei
 * @version  1.0
 */
@Service
@Slf4j
public class SysUserServiceImpl  implements SysUserService {
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    @Cacheable(cacheNames = "sysuser",key = "#root.method")
    public List<SysUser> findAllSysUser() {
        Map<String,Object> map=new HashMap<>();
        map.put("phone","18212164714");
        map.put("code","109822");
        rabbitTemplate.convertAndSend("phoneCodexchange", "phoneCodexRoute", map);
        return sysUserMapper.findAllSysUser();
    }


    @Override
    @Transactional
    public ResultUtils updateSysUser(SysUser sysUser,List<Integer> roleId) {
       if (StringEmptyUtils.isEmpty(sysUser.getUserPassword())) {
           String salt = sysUserMapper.findSysUserByIdSalt(sysUser.getId());
           String password = ShiroPasswordUtils.password(sysUser.getUserPassword(), salt);
           sysUser.setUserPassword(password);
       }
       if (sysUser.getId() == null) {
           return  ResultUtils.error(500,"主键id不能为空");
       }
        sysUser.setUpdateDate(new Date());
       if((!StringEmptyUtils.isEmpty(sysUser.getUserPassword()))&&(!StringEmptyUtils.isEmpty(sysUser.getUserName()))&&(sysUser.getSalt()==null)) {
           return  ResultUtils.error(500,"请你选择要修改的数据");
       }
        Integer updateSysUser = sysUserMapper.updateSysUser(sysUser);
        List<Integer> userId = sysUserRoleMapper.findUserRoleId(sysUser.getId());
        if (userId.size() > 0) {
            if (roleId!=null&&roleId.size() > 0) {
                  sysUserRoleMapper.deleteBYuserId(sysUser.getId());
                roleId.forEach((userRoleId)->{
                    SysUserRole role=new SysUserRole();
                    role.setUpdateDate(new Date());
                    role.setCreateDate(new Date());
                    role.setUserId(sysUser.getId());
                    role.setRoleId(userRoleId);
                    sysUserRoleMapper.insert(role);
                });
            }

        }
        if(updateSysUser>0){
            return  ResultUtils.ok();
        }
        return ResultUtils.error(500,"修改失败");
    }

    @Override
    public SysUser findSysUserByUserName(String userName) {
        return sysUserMapper.findSysUserByUserName(userName);
    }

    @Override
    public ResultUtils login(SysUser user) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUserName(), user.getUserPassword());
        try {
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            return  ResultUtils.error(500,"用户名不存在");
        } catch (AuthenticationException e) {
            return  ResultUtils.error(500,"账号或密码错误");
        } catch (AuthorizationException e) {
            return  ResultUtils.error(500,"没有权限");
        }
        List<Integer>  roleId = sysUserMapper.findRoleIdByuserName(user.getUserName());

        return ResultUtils.ok(roleId);
    }

    @Override
    public List<RolePerssionDTO> findRolePerssionByUserName(String userName) {
        return sysUserMapper.findRolePerssionByUserName(userName);
    }

    @Override
    public ResultUtils findUserRoleByNameData(String userName,Integer current,Integer size) {
       Map<String,Object> pageParams=new HashMap<String,Object>();
        if (current == null) {
            current = 1;
        }
        if (size == null ) {
            size = 10;
        }
        pageParams.put("current",current);
        pageParams.put("size",size);
        pageParams.put("userName",userName);
        List<SysUser> userRoleByNameOrAll = sysUserMapper.findUserRoleByNameOrAll(pageParams);
        Integer userRoleByNameOrAllCount = sysUserMapper.findUserRoleByNameOrAllCount(pageParams);
        return  PageUtils.pageInfo(userRoleByNameOrAll,userRoleByNameOrAllCount,current,size);

    }

    @Override
    @Transactional
    public ResultUtils deleteSysUserById(Integer id) {
        Integer sysUserId = sysUserMapper.deleteSysUserById(id);
        Integer roleUserId = sysUserRoleMapper.deleteBYuserId(id);
        if(id==null){
            return ResultUtils.error(500,"数据删除id不能为空");
        }
        if (sysUserId>0&&roleUserId>0) {
          return   ResultUtils.ok();
        }
        return ResultUtils.error(500,"删除失败");
    }

    @Override
    public ResultUtils saveSysUser(SysUser sysUser,Integer roleId) {
        SysUserRole sysUserRole=new SysUserRole();
        if (!StringEmptyUtils.isEmpty(sysUser.getUserName())) {
            return ResultUtils.error(500,"用户名不能为空");
        }
        if (!StringEmptyUtils.isEmpty(sysUser.getUserPassword())) {
            return ResultUtils.error(500,"密码不能为空");
        }
        String password = ShiroPasswordUtils.password(sysUser.getUserPassword(), sysUser.getUserName());
        sysUser.setUserPassword(password);
        sysUser.setCreateDate(new Date());
        sysUser.setUpdateDate(new Date());
        sysUser.setSalt(sysUser.getUserName());
        Integer user = sysUserMapper.insertSysUser(sysUser);
        sysUserRole.setUserId(sysUser.getId());
        sysUserRole.setRoleId(roleId);
        sysUserRole.setCreateDate(new Date());
        sysUserRole.setUpdateDate(new Date());
        int userRole = sysUserRoleMapper.insert(sysUserRole);
        if (userRole>0&&user>0) {
            return   ResultUtils.ok();
        }
        return ResultUtils.error(500,"新增失败");
    }


}
